import os

import pyaudio


def playPCM(file):
    # 初始化播放器
    p = pyaudio.PyAudio()
    stream = p.open(format=p.get_format_from_width(2), channels=1, rate=24000, output=True)
    # 将 audio 数据直接写入 PyAudio 的数据流
    with open(file, "rb") as f:
        stream.write(f.read())

    stream.stop_stream()
    stream.close()
    p.terminate()


def recursive_play(path):
    files = os.listdir(path)
    if len(files) == 0:
        return
    for file in files:
        new_path = '\\'.join([path, file])
        # 文件
        if os.path.isfile(new_path):
            if file.endswith(".audio"):
                print(new_path)
                playPCM(new_path)
        # 文件夹
        else:
            recursive_play(new_path)


if __name__ == '__main__':
    recursive_play("D:/test_data/TestData/basic_tts")
